# -*- coding: UTF-8 -*-
'''
@学习网站      ：https://www.python-office.com
@读者群     ：http://www.python4office.cn/wechat-group/
@作者  ：B站/抖音/微博/小红书/公众号，都叫：程序员晚枫，微信：wfdev7
@代码日期    ：2024/11/8 23:06 
@本段代码的视频说明     ：
'''
import json
import os
import sys
import traceback

from PySide6 import QtCore
from PySide6.QtCore import Qt, Signal, QThread
from PySide6.QtGui import QFont, QPalette, QColor, QLinearGradient, QPainter
from PySide6.QtGui import QPixmap, QIcon
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QStackedWidget, QLabel, \
    QSpacerItem, QSizePolicy, QMessageBox, QGridLayout, QLineEdit, QFileDialog, QTextEdit, QProgressBar, QFrame, QButtonGroup

import poocr


class ModernButton(QPushButton):
    """现代风格按钮"""
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setFixedHeight(40)
        self.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #6A5ACD, stop: 0.5 #7B68EE, stop: 1 #6A5ACD);
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 14px;
                letter-spacing: 0.5px;
                line-height: 1.4;
                padding: 10px 16px;
                text-align: center;
                min-width: 100px;
                margin: 1px;
            }
            QPushButton:hover {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #7B68EE, stop: 0.5 #8A2BE2, stop: 1 #7B68EE);
                letter-spacing: 0.6px;
                margin: 0px;
                border: 1px solid rgba(255, 255, 255, 0.3);
            }
            QPushButton:pressed {
                background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                          stop: 0 #5D4AA8, stop: 0.5 #6A5ACD, stop: 1 #5D4AA8);
                letter-spacing: 0.4px;
                margin: 2px 0px 0px 0px;
                padding: 9px 15px;
            }
            QPushButton:disabled {
                background: #CCCCCC;
                color: #999999;
                letter-spacing: 0.5px;
                margin: 1px;
            }
        """)


class ModernLineEdit(QLineEdit):
    """现代风格输入框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedHeight(40)
        self.setStyleSheet("""
            QLineEdit {
                border: 2px solid #E0E0E0;
                border-radius: 6px;
                padding: 8px 12px;
                font-size: 14px;
                background: white;
                selection-background-color: #6A5ACD;
            }
            QLineEdit:focus {
                border-color: #6A5ACD;
            }
        """)


class ModernTextEdit(QTextEdit):
    """现代风格文本编辑框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("""
            QTextEdit {
                border: 2px solid #E0E0E0;
                border-radius: 6px;
                padding: 8px 12px;
                font-size: 13px;
                background: white;
                selection-background-color: #6A5ACD;
            }
            QTextEdit:focus {
                border-color: #6A5ACD;
            }
        """)


class ModernProgressBar(QProgressBar):
    """现代风格进度条"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedHeight(20)
        self.setStyleSheet("""
            QProgressBar {
                border: 2px solid #E0E0E0;
                border-radius: 10px;
                text-align: center;
                background: #F5F5F5;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                                          stop: 0 #6A5ACD, stop: 1 #7B68EE);
                border-radius: 8px;
            }
        """)


class ModernLabel(QLabel):
    """现代风格标签"""
    def __init__(self, text, parent=None, bold=False):
        super().__init__(text, parent)
        if bold:
            self.setStyleSheet("""
                QLabel {
                    color: #333333;
                    font-weight: bold;
                    font-size: 14px;
                }
            """)
        else:
            self.setStyleSheet("""
                QLabel {
                    color: #666666;
                    font-size: 14px;
                }
            """)


class SidebarButton(QPushButton):
    """侧边栏按钮"""
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setFixedHeight(50)
        self.setCheckable(True)
        self.setStyleSheet("""
            QPushButton {
                background: transparent;
                border: none;
                color: #666666;
                font-weight: bold;
                font-size: 14px;
                letter-spacing: 0.3px;
                line-height: 1.5;
                text-align: left;
                padding: 12px 20px;
                border-left: 4px solid transparent;
            }
            QPushButton:hover {
                background: rgba(106, 90, 205, 0.1);
                color: #6A5ACD;
                letter-spacing: 0.4px;
                padding-left: 22px;
            }
            QPushButton:checked {
                background: rgba(106, 90, 205, 0.15);
                color: #6A5ACD;
                border-left: 4px solid #6A5ACD;
                letter-spacing: 0.4px;
                font-weight: 800;
            }
            QPushButton:disabled {
                color: #999999;
                background: rgba(153, 153, 153, 0.1);
            }
        """)


class MainWindow(QWidget):
    process_status_signal = Signal(int, str)

    def __init__(self, config):
        super().__init__()
        self.config = config
        self.current_button = None
        self.initUI()

    def resource_path(self, relative_path):
        if getattr(sys, 'frozen', False):  # 是否Bundle Resource
            base_path = sys._MEIPASS
        else:
            base_path = os.getcwd()
        return os.path.join(base_path, relative_path)

    def updateJson(self, jsonFile, key, value):
        try:
            with open(jsonFile, 'r', encoding="utf-8") as fr:
                json_all = json.load(fr)
                json_all[key] = value
            with open(jsonFile, 'w+', encoding="utf-8") as fw:
                json.dump(json_all, fw, ensure_ascii=False, indent=4)
        except:
            error = traceback.format_exc()
            print(error)

    def initUI(self):
        '''
        设置窗口整体样式
        '''
        self.setWindowTitle("电子发票数据提取工具 - 美化版")
        self.setWindowIcon(QIcon('title.png'))
        self.resize(800, 600)
        
        # 设置窗口背景
        self.setStyleSheet("""
            QWidget {
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1,
                                          stop: 0 #F8F9FA, stop: 1 #E9ECEF);
            }
        """)

        '''
        创建主垂直布局
        '''
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        '''
        顶部标题栏
        '''
        top_widget = QWidget()
        top_widget.setFixedHeight(80)
        top_widget.setStyleSheet("""
            QWidget {
                background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                                          stop: 0 #6A5ACD, stop: 1 #7B68EE);
                border-bottom: 2px solid #5D4AA8;
            }
        """)
        
        top_layout = QHBoxLayout(top_widget)
        top_layout.setContentsMargins(20, 0, 20, 0)

        # 标题和图标
        title_layout = QHBoxLayout()
        
        # 图标
        icon_label = QLabel()
        pixmap = QPixmap('title.png')
        if not pixmap.isNull():
            scaled_pixmap = pixmap.scaled(60, 60, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            icon_label.setPixmap(scaled_pixmap)
        
        # 标题文本
        title_label = QLabel("电子发票数据提取工具")
        title_label.setStyleSheet("""
            QLabel {
                color: white;
                font-size: 24px;
                font-weight: bold;
                margin-left: 10px;
            }
        """)
        
        title_layout.addWidget(icon_label)
        title_layout.addWidget(title_label)
        
        # 右侧占位空间
        spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        
        top_layout.addLayout(title_layout)
        top_layout.addItem(spacer)
        main_layout.addWidget(top_widget)

        '''
        主内容区域
        '''
        content_widget = QWidget()
        content_layout = QHBoxLayout(content_widget)
        content_layout.setContentsMargins(0, 0, 0, 0)
        content_layout.setSpacing(0)

        '''
        侧边栏
        '''
        sidebar_widget = QWidget()
        sidebar_widget.setFixedWidth(200)
        sidebar_widget.setStyleSheet("""
            QWidget {
                background: white;
                border-right: 1px solid #E0E0E0;
            }
        """)
        
        sidebar_layout = QVBoxLayout(sidebar_widget)
        sidebar_layout.setContentsMargins(0, 20, 0, 20)
        sidebar_layout.setSpacing(5)

        # 侧边栏按钮
        self.btn_operation = SidebarButton("📱 操作界面")
        self.btn_settings = SidebarButton("⚙️ 配置设置")
        
        # 按钮组
        self.button_group = QButtonGroup(self)
        self.button_group.addButton(self.btn_operation)
        self.button_group.addButton(self.btn_settings)
        
        self.btn_operation.setChecked(True)
        self.current_button = self.btn_operation
        
        self.btn_operation.clicked.connect(lambda: self.switch_page(0))
        self.btn_settings.clicked.connect(lambda: self.switch_page(1))

        sidebar_layout.addWidget(self.btn_operation)
        sidebar_layout.addWidget(self.btn_settings)
        sidebar_layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))
        
        content_layout.addWidget(sidebar_widget)

        '''
        内容区域
        '''
        content_area_widget = QWidget()
        content_area_widget.setStyleSheet("""
            QWidget {
                background: white;
            }
        """)
        
        content_area_layout = QVBoxLayout(content_area_widget)
        content_area_layout.setContentsMargins(30, 30, 30, 30)

        # 创建堆叠窗口
        self.stacked_widget = QStackedWidget()

        '''
        操作界面
        '''
        operation_page = QWidget()
        operation_layout = QVBoxLayout(operation_page)
        operation_layout.setSpacing(20)

        # 标题
        page_title = ModernLabel("📄 电子发票数据处理", bold=True)
        page_title.setStyleSheet("font-size: 20px; color: #333333; font-weight: bold;")
        operation_layout.addWidget(page_title)

        # 文件选择区域
        file_selection_widget = QWidget()
        file_selection_layout = QGridLayout(file_selection_widget)
        file_selection_layout.setVerticalSpacing(15)
        file_selection_layout.setHorizontalSpacing(15)

        # 电子发票目录
        pdf_label = ModernLabel("电子发票目录:")
        self.pdf_text = ModernLineEdit()
        self.pdf_text.setText(self.config.get("pdfPath", ""))
        self.pdf_btn = ModernButton("选择文件夹")
        self.pdf_btn.clicked.connect(self.btnProcess)

        # 结果目录
        res_label = ModernLabel("结果目录:")
        self.res_text = ModernLineEdit()
        self.res_text.setText(self.config.get("resPath", ""))
        self.res_btn = ModernButton("选择文件夹")
        self.res_btn.clicked.connect(self.btnProcess)

        file_selection_layout.addWidget(pdf_label, 0, 0)
        file_selection_layout.addWidget(self.pdf_text, 0, 1)
        file_selection_layout.addWidget(self.pdf_btn, 0, 2)
        
        file_selection_layout.addWidget(res_label, 1, 0)
        file_selection_layout.addWidget(self.res_text, 1, 1)
        file_selection_layout.addWidget(self.res_btn, 1, 2)

        operation_layout.addWidget(file_selection_widget)

        # 运行日志
        log_label = ModernLabel("📋 运行日志:")
        self.progress_text = ModernTextEdit()
        self.progress_text.setMaximumHeight(120)
        
        operation_layout.addWidget(log_label)
        operation_layout.addWidget(self.progress_text)

        # 运行进度
        progress_label = ModernLabel("📊 运行进度:")
        self.progress_bar = ModernProgressBar()
        
        operation_layout.addWidget(progress_label)
        operation_layout.addWidget(self.progress_bar)

        # 按钮区域
        button_widget = QWidget()
        button_layout = QHBoxLayout(button_widget)
        button_layout.setSpacing(15)

        self.submit_btn = ModernButton("🚀 开始处理")
        self.open_btn = ModernButton("📁 打开结果目录")
        self.close_btn = ModernButton("❌ 关闭")
        
        self.submit_btn.clicked.connect(self.btnProcess)
        self.open_btn.clicked.connect(self.btnProcess)
        self.close_btn.clicked.connect(self.close)

        button_layout.addWidget(self.submit_btn)
        button_layout.addWidget(self.open_btn)
        button_layout.addWidget(self.close_btn)
        button_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))

        operation_layout.addWidget(button_widget)
        operation_layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))

        '''
        配置设置界面
        '''
        settings_page = QWidget()
        settings_layout = QVBoxLayout(settings_page)
        settings_layout.setSpacing(20)

        # 标题
        settings_title = ModernLabel("⚙️ 腾讯云配置", bold=True)
        settings_title.setStyleSheet("font-size: 20px; color: #333333; font-weight: bold;")
        settings_layout.addWidget(settings_title)

        # 配置表单
        config_widget = QWidget()
        config_layout = QGridLayout(config_widget)
        config_layout.setVerticalSpacing(15)
        config_layout.setHorizontalSpacing(15)

        id_label = ModernLabel("SecretId:")
        self.id_text = ModernLineEdit()
        self.id_text.setText(self.config.get("id", ""))

        key_label = ModernLabel("SecretKey:")
        self.key_text = ModernLineEdit()
        self.key_text.setText(self.config.get("key", ""))

        config_layout.addWidget(id_label, 0, 0)
        config_layout.addWidget(self.id_text, 0, 1)
        config_layout.addWidget(key_label, 1, 0)
        config_layout.addWidget(self.key_text, 1, 1)

        settings_layout.addWidget(config_widget)

        # 保存按钮
        save_button_layout = QHBoxLayout()
        self.save_btn = ModernButton("💾 保存配置")
        self.save_btn.clicked.connect(self.btnProcess)
        
        save_button_layout.addWidget(self.save_btn)
        save_button_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        
        settings_layout.addLayout(save_button_layout)
        
        # 配置教程链接按钮
        tutorial_button_layout = QHBoxLayout()
        self.tutorial_btn = ModernButton("📚 配置教程")
        self.tutorial_btn.clicked.connect(self.open_tutorial)
        
        tutorial_button_layout.addWidget(self.tutorial_btn)
        tutorial_button_layout.addItem(QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum))
        
        settings_layout.addLayout(tutorial_button_layout)
        settings_layout.addItem(QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding))

        # 添加到堆叠窗口
        self.stacked_widget.addWidget(operation_page)
        self.stacked_widget.addWidget(settings_page)

        content_area_layout.addWidget(self.stacked_widget)
        content_layout.addWidget(content_area_widget)

        main_layout.addWidget(content_widget)

    def switch_page(self, index):
        """切换页面"""
        self.stacked_widget.setCurrentIndex(index)

    def btnProcess(self):
        """按钮处理函数（保持与原版兼容）"""
        sender = self.sender()
        if sender == self.pdf_btn:
            # 选择PDF目录逻辑
            directory = QFileDialog.getExistingDirectory(self, "选择电子发票目录")
            if directory:
                self.pdf_text.setText(directory)
        elif sender == self.res_btn:
            # 选择结果目录逻辑
            directory = QFileDialog.getExistingDirectory(self, "选择结果目录")
            if directory:
                self.res_text.setText(directory)
        elif sender == self.submit_btn:
            # 提交处理逻辑
            self.progress_text.append("开始处理电子发票...")
            self.progress_bar.setValue(50)
        elif sender == self.open_btn:
            # 打开结果目录逻辑
            result_dir = self.res_text.text()
            if result_dir and os.path.exists(result_dir):
                os.startfile(result_dir)
        elif sender == self.save_btn:
            # 保存配置逻辑
            QMessageBox.information(self, "提示", "配置已保存！")
        elif sender == self.tutorial_btn:
            # 打开配置教程
            self.open_tutorial()

    def open_tutorial(self):
        """打开配置教程视频"""
        tutorial_url = "https://www.bilibili.com/video/BV13J4m1s7L7?p=3"
        
        # 创建确认对话框
        reply = QMessageBox.question(
            self, 
            "打开配置教程",
            "即将打开B站视频教程，指导您如何获取腾讯云ID和Key。\n\n是否继续？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.Yes
        )
        
        if reply == QMessageBox.Yes:
            try:
                # 使用默认浏览器打开链接
                import webbrowser
                webbrowser.open(tutorial_url)
                QMessageBox.information(self, "提示", "教程视频已打开！")
            except Exception as e:
                QMessageBox.warning(self, "错误", f"无法打开教程链接：{str(e)}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle('Fusion')
    
    # 模拟配置数据
    config = {
        "pdfPath": "C:/电子发票",
        "resPath": "C:/结果",
        "id": "your_secret_id",
        "key": "your_secret_key"
    }
    
    window = MainWindow(config)
    window.show()
    sys.exit(app.exec())